import 'dart:developer';
import 'dart:io';

import 'package:fate_blind_box/chat_view/actions.dart';
import 'package:fate_blind_box/chat_view/record_panel.dart';
import 'package:fate_blind_box/chat_view/video_push_widget.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/config/app_utils.dart';
import 'package:fate_blind_box/config/event_bus.dart';
import 'package:fate_blind_box/config/event_keys.dart';
import 'package:fate_blind_box/im/ProviderChatContent.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/utils/snack_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:video_player/video_player.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import 'dialog.dart';
import 'emoji_panel.dart';
import 'more_panel.dart';

class ChatInput extends StatefulWidget {
  final ProviderChatContent? providerChatContent;
  final String conversationId;
  final ChatType type;
  final List<ActionItem>? moreAction;

  const ChatInput({
    super.key,
    this.providerChatContent,
    required this.conversationId,
    this.type = ChatType.Chat,
    this.moreAction,
  });

  @override
  State<ChatInput> createState() => _ChatInputState();
}

class _ChatInputState extends State<ChatInput> {
  final TextEditingController _textEditingController = TextEditingController();

  final FocusNode _focusNode = FocusNode();
  final bool _isKeyboardVisible = false;
  final double _keyboardHeight = 0.0;

  /// none, input, record, emoji, more
  String _currentType = ActionConstants.none;

  bool? get keyBoarShow => widget.providerChatContent?.contentShow;

  ScrollController scrollController = ScrollController();

  // 快捷图片选择器
  final ImagePicker _picker = ImagePicker();

  // 是都正在录制

  @override
  void initState() {
    super.initState();
    EventBus.instance.addListener(EventKeys.offKeyBoard, (arg) {
      setState(() {
        _currentType = ActionConstants.none;
      });
    });
  }

  @override
  void dispose() {
    // 移除键盘状态监听器
    super.dispose();
    EventBus.instance.removeListener(eventName: EventKeys.offKeyBoard);
  }

  List<ActionItem> _defaultInputActions() {
    return [
      ActionItem(
          type: ActionConstants.record,
          icon: _actionIcon('images/ic_send_voice.png', ActionConstants.record),
          onTap: _onRecordActionTap),
      ActionItem(
          type: ActionConstants.emoji,
          icon: _actionIcon('images/ic_send_emoji.png', ActionConstants.emoji),
          onTap: _onEmojiActionTap),
      ActionItem(
          type: ActionConstants.image,
          icon: _actionIcon('images/ic_send_image.png', ActionConstants.image),
          onTap: _onImageActionTap),
      ActionItem(
          type: ActionConstants.more,
          icon: _actionIcon('images/ic_add.png', ActionConstants.more),
          onTap: _onMoreActionTap),
    ];
  }

  Widget _actionIcon(String iconPath, String type) {
    return Image.asset(
      iconPath,
      width: 24.w,
      height: 24.w,
    );
  }

  /// 关闭键盘
  offKeyBoard() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
    if (_focusNode.hasFocus) {
      _focusNode.unfocus();
    }
  }

  // 录音
  _onRecordActionTap(BuildContext context) async {
    if (Platform.isAndroid) {
      var status = await AppUtils.permissionCheck(Permission.microphone);
      if (status != true) {
        var value = await permissionDialog(
          context,
          title: "“都肆商圈”需要使用您的麦克风权限，是否允许？",
          content: '不允许您将无法发送语音消息',
        );
        if (value == '不允许') {
          return;
        }
      }
    }
    requestMicrophonePermissionOnStart();
  }

  // 表情
  _onEmojiActionTap(BuildContext context) {
    offKeyBoard();
    if (_currentType == ActionConstants.emoji) {
      AppUtils.isShowKeyboard = false;
      _currentType = ActionConstants.none;
    } else {
      AppUtils.isShowKeyboard = true;
      _currentType = ActionConstants.emoji;
    }
    setState(() {});
  }

  _onImageActionTap(BuildContext context) {
    offKeyBoard();
    var style = TextStyle(fontSize: 16, color: '#333333'.stringToColor);
    showBottomChoose<String>(
            context: context,
            actions: [
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, '照片');
                },
                child: Text(
                  '照片',
                  style: style,
                ),
              ),
              CupertinoActionSheetAction(
                onPressed: () {
                  Navigator.pop(context, '视频');
                },
                child: Text(
                  '视频',
                  style: style,
                ),
              ),
            ],
            showCancel: true)
        .then((value) => checkLimits(value));
  }

  // 更多选项
  _onMoreActionTap(BuildContext context) {
    offKeyBoard();
    // EasyLoading.showToast('敬请期待');
    // return;
    if (_currentType == ActionConstants.more) {
      _currentType = ActionConstants.none;
    } else {
      _focusNode.unfocus();
      _currentType = ActionConstants.more;
    }
    setState(() {});
  }

  // 权限检查
  checkLimits(String? type) async {
    bool isGranted = await AppUtils.permissionPhotos();
    if (isGranted) {
      if (type == '照片') {
        _pickImage();
      } else if (type == '视频') {
        _pickVideoFromPhoto();
      }
    } else {
      permissionTips(type);
    }
  }

  // 权限申请
  permissionTips(String? type) async {
    if (Platform.isAndroid) {
      var status = await permissionDialog(
        context,
        title: "“都肆商圈”需要使用您的相册权限，是否允许？",
        content: '不允许您将无法发送图片消息',
      );
      if (status == '不允许') {
        return;
      }
    }
    requestPermission(type);
  }

  ///申请权限
  void requestPermission(String? type) async {
    var permission = await AppUtils.getPhotoPermission();
    PermissionStatus status = await permission.request();
    if (status.isGranted) {
      if (type == '照片') {
        _pickImage();
      } else if (type == '视频') {
        _pickVideoFromPhoto();
      }
    } else {
      // openAppSettings();
    }
  }

  /// 选择照片
  _pickImage() async {
    final List<XFile>? pickedFileList = await _picker.pickMultiImage();
    if (pickedFileList != null) {
      for (XFile image in pickedFileList) {
        File file = File(image.path);
        final size = await AppUtils.getImageSize(file);
        int len = await image.length();
        _sendImageMessage(
          image.path,
          len,
          size.width,
          size.height,
        );
      }
    }
  }

  /// 从微信朋友圈选择
  _pickVideoFromPhoto() async {
    FilterOptionGroup optionGroup = FilterOptionGroup()
      ..containsLivePhotos = false;
    final List<AssetEntity>? entities = await AssetPicker.pickAssets(context,
        pickerConfig: AssetPickerConfig(
            maxAssets: 1,
            requestType: RequestType.video,
            filterOptions: optionGroup));
    if (entities == null) return;
    for (AssetEntity entity in entities) {
      File? file = await entity.file;
      if (file == null) return;
      VideoPlayerController controller = VideoPlayerController.file(file);
      controller.initialize().then((value) async {
        var urlPath = await VideoThumbnail.thumbnailFile(
          video: file.path,
          imageFormat: ImageFormat.PNG,
          maxWidth: 260,
          // specify the width of the thumbnail, let the height auto-scaled to keep the source aspect ratio
          quality: 10,
        );
        EMMessage message = EMMessage.createVideoSendMessage(
          targetId: widget.conversationId,
          filePath: file.path,
          duration: controller.value.duration.inSeconds,
          width: controller.value.size.width.toDouble(),
          height: controller.value.size.height.toDouble(),
          thumbnailLocalPath: urlPath,
          chatType: widget.type,
        );
        _sendVideoImage(message);
        // 释放资源
        controller.dispose();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: MediaQuery.of(context).size.width,
      color: Colors.white,
      child: SafeArea(
        child: Column(
          children: [
            AnimatedContainer(
              duration: const Duration(milliseconds: 100),
              curve: Curves.easeInOut,
              height: _isKeyboardVisible ? _keyboardHeight + 60 : 60,
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 12.w),
                child: Row(
                  children: [
                    Expanded(
                        child: TextField(
                      controller: _textEditingController,
                      decoration: InputDecoration(
                        contentPadding: const EdgeInsets.symmetric(
                            vertical: 9, horizontal: 12),
                        fillColor: ThemeColor.color19CF8F23,
                        filled: true,
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide.none),
                        isDense: true,
                        hintText: '输入消息内容…',
                        hintStyle: TextStyle(
                            color: const Color(0xffb3b7bc), fontSize: 12.sp),
                      ),
                      maxLines: 1,
                      textInputAction: TextInputAction.send,
                      enabled: true,
                      onChanged: (value) {},
                      style: TextStyle(
                          color: '#333333'.stringToColor, fontSize: 16),
                      onTap: () {
                        if (_currentType != ActionConstants.none) {
                          setState(() {
                            _currentType = ActionConstants.none;
                          });
                        }
                      },
                    )),
                    SizedBox(width: 10.w),
                    ElevatedButton(
                      style: ElevatedButton.styleFrom(
                        backgroundColor: ThemeColor.colorCF8F23,
                      ),
                      onPressed: () {
                        setState(() {
                          FocusScopeNode currentFocus = FocusScope.of(context);
                          if (!currentFocus.hasPrimaryFocus &&
                              currentFocus.focusedChild != null) {
                            FocusManager.instance.primaryFocus?.unfocus();
                          }
                          if (_focusNode.hasFocus) {
                            _focusNode.unfocus();
                          }
                          widget.providerChatContent?.updateContentShow(true);
                          _sendTextMessage();
                        });
                      },
                      child: const Text('发送'),
                    ),
                  ],
                ),
              ),
            ),
            Row(
              children: _defaultInputActions()
                  .map((action) => Expanded(
                          child: InputTextAction(
                        action: action,
                        enable: true,
                        onTap: () {
                          _scrollToBottom();
                          if (action.onTap != null) {
                            action.onTap!(context);
                          }
                        },
                      )))
                  .toList(),
            ),
            AnimatedContainer(
              duration: const Duration(milliseconds: 100),
              height: _getPanelHeight(),
              child: _getPanel(),
            )
          ],
        ),
      ),
    );
  }

  /// 发送文本消息
  _sendTextMessage() async {
    final text = _textEditingController.text.trim();
    if (text.isNotEmpty) {
      EMMessage message = EMMessage.createTxtSendMessage(
        targetId: widget.conversationId,
        content: text,
        chatType: widget.type,
      );
      bool status = await EMClient.getInstance.isConnected();
      if (status) {
        log('环信连接成功准备发送消息: ${message.body}');
        EMClient.getInstance.chatManager.sendMessage(message).then((value) {
          EventBus.instance.commit(
              eventName: EventKeys.chatUpdateAudioMessage, data: message);
        });
      } else {
        ThemeSnackBar.show(context, '已断线,请重新登陆~');
        FocusScope.of(context).unfocus();
        await EMClient.getInstance
            .login(Provider.userEaseName, Provider.userEaseToken, false);
      }
      _textEditingController.clear();
    } else {
      EasyLoading.showToast('请输入');
    }
    _scrollToBottom();
  }

  /// 发送图片
  _sendImageMessage(
      String filePath, int fileSize, int width, int height) async {
    EMMessage message = EMMessage.createImageSendMessage(
      targetId: widget.conversationId,
      filePath: filePath.toString(),
      fileSize: fileSize,
      width: width.toDouble(),
      height: height.toDouble(),
      chatType: widget.type,
    );
    bool status = await EMClient.getInstance.isConnected();
    if (status) {
      log('环信连接${status ? '成功' : '失败'}准备发送图片消息');
      EMClient.getInstance.chatManager.sendMessage(message).then((value) {
        log('图片消息发送完毕:$value');
        EventBus.instance
            .commit(eventName: EventKeys.chatUpdateAudioMessage, data: message);
      });
    } else {
      ThemeSnackBar.show(context, '已断线,请重新登陆~');
      await EMClient.getInstance
          .login(Provider.userEaseName, Provider.userEaseToken, false);
      FocusScope.of(context).unfocus();
    }
  }

  /// 发送视频
  _sendVideoImage(EMMessage message) async {
    bool status = await EMClient.getInstance.isConnected();
    if (status) {
      log('环信连接成功准备发送视频消息:$message');
      EMClient.getInstance.chatManager.sendMessage(message).then((value) {
        log('视频消息发送完毕:$value');
        EventBus.instance
            .commit(eventName: EventKeys.chatUpdateAudioMessage, data: message);
      });
    } else {
      ThemeSnackBar.show(context, '已断线,请重新登陆~');
      await EMClient.getInstance
          .login(Provider.userEaseName, Provider.userEaseToken, false);
      FocusScope.of(context).unfocus();
    }
  }

  /// 底部菜单控制器
  Widget _getPanel() {
    if (_currentType == ActionConstants.record) {
      return RecordPanel(
        onPressedDown: () {
          setState(() {});
        },
        onEnd: () {
          setState(() {});
        },
        onCancel: () {
          setState(() {});
        },
        conversationId: widget.conversationId,
        type: widget.type,
      );
    }
    if (_currentType == ActionConstants.emoji) {
      return EmojiPanel(
        onEmojiSelected: (emoji) {
          final text = _textEditingController.text;
          _textEditingController.text = "$text$emoji";
        },
        onEmojiDelete: () {
          String originText = _textEditingController.text;
          var text = originText.characters.skipLast(1);
          _textEditingController.text = "$text";
        },
        onEmojiSendClick: _sendTextMessage,
      );
    }
    if (_currentType == ActionConstants.more) {
      return MorePanel(
        moreActions: widget.moreAction,
        keepDefault: false,
      );
    }
    return Container();
  }

  double _getPanelHeight() {
    if (_currentType == ActionConstants.record ||
        _currentType == ActionConstants.more ||
        _currentType == ActionConstants.emoji) {
      return 197;
    }
    return 0;
  }

  void _scrollToBottom() {
    Future.delayed(const Duration(milliseconds: 16), () {
      if (scrollController.positions.isNotEmpty &&
          scrollController.positions.length == 1) {
        scrollController.animateTo(
          scrollController.position.minScrollExtent,
          duration: const Duration(milliseconds: 200),
          curve: Curves.ease,
        );
      }
    });
  }

  Future<void> requestMicrophonePermissionOnStart() async {
    final status = await Permission.microphone.request();
    if (status.isGranted) {
      // 麦克风权限已授予, 在此处执行相应的操作，例如开始录音等
      offKeyBoard();
      if (_currentType == ActionConstants.record) {
        AppUtils.isShowKeyboard = false;
        _currentType = ActionConstants.none;
      } else {
        AppUtils.isShowKeyboard = true;
        _currentType = ActionConstants.record;
      }
      setState(() {});
    } else if (status.isDenied) {
      // 麦克风权限被拒绝
      // 可以显示一个提示来解释为什么需要麦克风权限，并引导用户手动授予权限
      showDialog();
    } else if (status.isPermanentlyDenied) {
      showDialog();
    }
  }

  showDialog() {
    showCupertinoDialog(
      //点击空白处取消
      barrierDismissible: true,
      context: context,
      builder: (context) {
        return CupertinoAlertDialog(
          title: const Text("语音聊天请先开启麦克风权限"),
          actions: [
            CupertinoDialogAction(
              child: Text(
                "取消",
                style: TextStyle(
                    color: Colors.red,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            CupertinoDialogAction(
              child: Text(
                "设置",
                style: TextStyle(
                    color: Colors.blue,
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                openAppSettings();
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }
}
